import React, { useState, useEffect } from "react";
import { Form, Input, Button, Toast } from "antd-mobile";
import { connect } from "react-redux";
import action from "../store/action";
import "./Login.less";
import api from "@/api";
import utils from "@/assets/utils";
import NavBarAgain from "../components/NavBarAgain";
// 自定义表单校验规则
const validate = {
  phone(_, value) {
    value = value.trim();
    let reg = /^(?:(?:\+|00)86)?1\d{10}$/;
    if (value.length === 0) return Promise.reject(new Error("手机号是必填项!"));
    if (!reg.test(value)) return Promise.reject(new Error("手机号格式有误!"));
    return Promise.resolve();
  },
  code(_, value) {
    value = value.trim();
    let reg = /^\d{6}$/;
    if (value.length === 0) return Promise.reject(new Error("验证码是必填项!"));
    if (!reg.test(value)) return Promise.reject(new Error("验证码格式有误!"));
    return Promise.resolve();
  },
};
const Login = function Login(props) {
  // 派发redux中的值后就可以通过props获取我们想要的数据了
  const { queryUserInfoAsync, navigate, usp } = props;
  // 获取表单实例
  const [formIns] = Form.useForm();
  const [codeBtn, setCodeBtn] = useState(false);
  const [codeText, setCodeText] = useState("发送验证码");
  let timer = null,
    num = 30;
  // 发送验证码：
  const sendCode = async () => {
    // await formIns.validateFields(["phone"]);
    //调用发送验证码的接口
    // 获取输入的手机号
    const phoneNum = formIns.getFieldValue("phone");
    const phoneCode = await api.sendPhoneCode(phoneNum);
    if (phoneCode.code === 0) {
      Toast.show({
        icon: "success",
        content: "验证码发送成功",
      });
    }
    // 设置按钮的状态为disabled
    setCodeBtn(true);
    //设置按钮为倒计时
    timer = setInterval(() => {
      num--;
      setCodeText(`${num}秒后重新发送`);
      //如果倒计时已经为0
      if (num === 0) {
        // 清除定时器
        clearInterval(timer);
        timer = null;
        setCodeBtn(false); // 按钮可点
        setCodeText("发送验证码");
      }
    }, 1000);
  };
  // 表单提交
  const submit = async () => {
    const { phone, code } = formIns.getFieldsValue(["phone", "code"]);
    // 调用登录接口
    const login = await api.login(phone, code);
    if (login.code === 0) {
      // 把Token存储到localStorage
      utils.storage.set("token", login.token);
    }
    await queryUserInfoAsync(); //派发任务，同步redux中的状态信息
    // 提示
    Toast.show({
      icon: "success",
      content: "登录/注册成功",
    });
    // 跳转
    navigate(-1);
  };
  // 如果页面中有定时器或绑定了DOM元素，一定要再再组件销毁的时候清除定时器或Dom元素
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    };
  }, []);
  return (
    <div className="login-box">
      <NavBarAgain back={""} backArrow={true} title={"登录/注册"}></NavBarAgain>
      {/* 表单 */}
      <Form
        layout="horizontal"
        form={formIns}
        initialValues={{ phone: "", code: "" }}
        footer={
          <Button block color="primary" onClick={submit} size="large">
            提交
          </Button>
        }
      >
        <Form.Item
          name="phone"
          label="手机号"
          rules={[{ validator: validate.phone }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          name="code"
          label="验证码"
          rules={[{ validator: validate.code }]}
          extra={
            <Button color="primary" disabled={codeBtn} onClick={sendCode}>
              {codeText}
            </Button>
          }
        >
          <Input placeholder="请输入验证码" />
        </Form.Item>
      </Form>
    </div>
  );
};
// 派发的是action文件夹下base.js中的内容
export default connect(null, action.base)(Login);
